<template>
  <div class="users-base-wrapper">
    <div class="details-layout">
      <div class="search-bar">
        <el-form :inline="true" size="mini" :model="filters" label-width="100px" @submit.native.prevent>
          <el-row :span="24">
            <el-col :span="8">
              <el-form-item label="eCRF表单：">
                <el-select v-model="filters.surface" placeholder="请选择" style="width: 220px" clearable>
                  <el-option v-for="item in eCRFDesignList" :key="item.surface" :value="item.surface">
                    <span style="float: left">{{ item.surfaceName }}({{ item.surface }})</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-button type="primary" size="mini" @click="handleSearch">查询</el-button>
              <el-button type="default" size="mini" @click="handleResent">重置</el-button>
              <el-button type="primary" size="mini" @click="handleTakeEffect" v-if="isLock !== '1'">生效</el-button>
              <el-button type="primary" size="mini" @click="handleLoseEfficacy" v-if="isLock !== '1'">失效</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-table
        :data="checkTypeList"
        :stripe="true"
        :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        height="720"
      >
        <el-table-column type="selection" width="55" align="center"> </el-table-column>
        <el-table-column type="index" label="序号" align="center" width="50"> </el-table-column>
        <el-table-column prop="surface" align="center" label="表" width="80"></el-table-column>
        <el-table-column prop="surfaceName" align="center" label="表名" width="100"></el-table-column>
        <el-table-column prop="variable" align="center" label="变量" width="80"></el-table-column>
        <el-table-column prop="variableName" align="center" label="变量名称" width="100"></el-table-column>
        <el-table-column prop="takeEffect" align="center" label="是否生效" width="80">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.takeEffect === '1'">生效</el-tag>
            <el-tag type="info" v-if="scope.row.takeEffect === '0'">失效</el-tag>
          </template>
        </el-table-column>
        <!-- 本表条件 -->
        <el-table-column prop="thisTable" align="center" label="本表条件" width="250">
          <template slot-scope="scope">
            <el-input disabled size="mini" v-model="scope.row.thisTableCn" style="width: 100px"></el-input>
            <el-button size="mini" style="margin-left: 4px" @click="handleTableConditionVisible(scope.row)"
              >...</el-button
            >
          </template>
        </el-table-column>
        <!-- 跨表条件 -->
        <el-table-column prop="roleId" align="center" label="跨表条件" width="250">
          <template slot-scope="scope">
            <el-input disabled size="mini" v-model="scope.row.crossTableCn" style="width: 100px"></el-input>
            <el-button size="mini" style="margin-left: 4px" @click="handleCrossTableConditionVisible(scope.row)"
              >...</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="preconditions" align="center" label="前置条件" width="200"></el-table-column>
        <el-table-column prop="roleId" align="center" label="质疑方式" width="120">
          <template slot-scope="scope">
            <el-select size="mini" v-model="scope.row.way" placeholder="请选择" style="width: 80px">
              <el-option
                v-for="item in questioningModeList"
                :key="item.value"
                :value="item.value"
                :label="item.text"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <div v-if="isLock !== '1'">
              <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="text" @click="handleCopy(scope.row)">复制</el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <add-record
      :dialogVisible="dialogVisible"
      :dialogTitle="dialogTitle"
      :editData="editData"
      :questioningModeList="questioningModeList"
      :searchParams="searchParams"
      @handleCancel="handleCancel"
    ></add-record>
    <TableCondition
      :tableVisible="tableVisible"
      :rowData="rowData"
      actionType="updateThisTableCrossTableControlledAPI"
      @handleTableConditionCancel="handleTableConditionCancel"
    ></TableCondition>
    <CrossTableCondition
      :crossVisible="crossVisible"
      :rowData="rowData"
      actionType="updateThisTableCrossTableControlledAPI"
      @handleCrossTableConditionCancel="handleCrossTableConditionCancel"
    ></CrossTableCondition>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import addRecord from './component/add-record.vue'
import TableCondition from '../../components/table-condition'
import CrossTableCondition from '../../components/cross-table-condition'

export default {
  name: 'filled-page',
  components: {
    addRecord,
    TableCondition,
    CrossTableCondition,
  },
  data() {
    return {
      checkTypeList: [],
      roleList: [],
      questioningModeList: [
        {
          text: '中心',
          value: 0,
        },
        {
          text: 'DM',
          value: 1,
        },
        {
          text: '提示',
          value: 2,
        },
      ],
      filters: {
        surface: '',
      },
      eCRFDesignList: [],
      dialogVisible: false,
      editData: {},
      dialogTitle: '',
      searchParams: {},
      tableVisible: false,
      rowData: {},
      crossVisible: false,
      databaseInfo: {},
      isLock: '1',
      // 选择的行
      multipleSelection: [],
    }
  },
  mounted() {
    this.databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.isLock = this.databaseInfo.isLock
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.searchParams = {
      projectId: localStorage.getItem('sys-project-id') || '',
      ...databaseInfo,
    }
    this.getControlledFieldList()
    this.getDesignList()
  },

  methods: {
    ...mapActions('verificationRule', [
      'qryControlledFieldList',
      'deleteControlledField',
      'getTableConditionOptionsAPI', // 本表首个下拉
      'getNowConfigVisitAPI', // 跨表访视
      'getVisitTableListAPI', // 跨表表单
      'updateStatusAllControlledAPI',
    ]),
    ...mapActions('eCRFDesign', ['qryDesignList', 'qryVariableConfigListNoLoading']),

    // 点击选择框
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 打开本表条件
    handleTableConditionVisible(row) {
      this.tableVisible = true
      this.rowData = row
    },

    // 本表条件取消
    handleTableConditionCancel(type) {
      this.tableVisible = false
      if (type === 'refresh') {
        this.getControlledFieldList()
      }
    },

    // 打开跨表条件
    handleCrossTableConditionVisible(row) {
      this.rowData = row
      this.crossVisible = true
    },

    // 跨表条件取消
    handleCrossTableConditionCancel(type) {
      this.crossVisible = false
      if (type === 'refresh') {
        this.getControlledFieldList()
      }
    },

    // 查询未填写（受控字段）列表
    getControlledFieldList() {
      const params = {
        ...this.searchParams,
        ...this.filters,
      }
      this.qryControlledFieldList({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.checkTypeList = data
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    // 查询eCRF表单列表
    getDesignList() {
      const params = {
        ...this.searchParams,
        embedded: '',
      }
      this.qryDesignList({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.eCRFDesignList = data
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    // 查询
    handleSearch() {
      this.getControlledFieldList()
    },

    // 重置查询条件
    handleResent() {
      this.filters.surface = ''
    },

    // 生效按钮
    async handleTakeEffect() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请先选择数据！')
      }
      const data = {
        projectId: localStorage.getItem('sys-project-id') || '',
        ...this.databaseInfo,
        takeEffect: '1',
        ids: this.multipleSelection.map(item => item.id),
      }
      const res = await this.updateStatusAllControlledAPI({ data })
      if (res.code === 200) {
        this.$message.success('生效成功！')
        this.getControlledFieldList()
      }
    },

    // 失效按钮
    async handleLoseEfficacy() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请先选择数据！')
      }
      const data = {
        projectId: localStorage.getItem('sys-project-id') || '',
        ...this.databaseInfo,
        takeEffect: '0',
        ids: this.multipleSelection.map(item => item.id),
      }
      const res = await this.updateStatusAllControlledAPI({ data })
      if (res.code === 200) {
        this.$message.success('失效成功！')
        this.getControlledFieldList()
      }
    },

    // 取消
    handleCancel(type) {
      this.dialogVisible = false
      if (type === 'refresh') {
        this.getControlledFieldList()
      }
    },

    // 编辑
    handleEdit(record) {
      this.editData = record
      this.dialogVisible = true
      this.dialogTitle = '编辑'
    },

    // 复制
    handleCopy(record) {
      this.editData = record
      this.dialogVisible = true
      this.dialogTitle = '复制'
    },

    handleDelete(row) {
      const params = {
        id: row.id,
      }
      this.$confirm('确定删除该条数据吗？', '删除提示', {
        type: 'warning',
      }).then(res => {
        this.deleteControlledField({ params }).then(res => {
          if (res.code === 200) {
            this.$message({ message: '删除成功', type: 'success' })
            this.getControlledFieldList()
          }
        })
      })
    },
  },
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
